package com.wangzhenyu.learn.test.designPattern

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy


//代理模式


//静态代理
@Suppress("UNUSED")
object MProxyPattern {

    interface ITeacherDao {
        fun teacher()
    }

    class TeacherDao : ITeacherDao {

        override fun teacher() {
            println("教师正在授课")
        }
    }

    class TeacherDaoProxy(private val target: ITeacherDao) : ITeacherDao {

        override fun teacher() {

            println("开始代理.....")
            target.teacher()

        }
    }

}

//动态代理
@Suppress("UNUSED")
object MProxyPattern02 {

    interface ITeacherDao {
        fun teacher(name: String)
    }

    class TeacherDao : ITeacherDao {

        override fun teacher(name: String) {
            println("教师$name 正在授课")
        }
    }

    class ProxyFactory(private val target: Any) {

        fun getProxyInstance(): Any {
            return Proxy.newProxyInstance(
                target.javaClass.classLoader,
                target.javaClass.interfaces
            ) { _, method, args ->

                println("JDK 代理开始")
                return@newProxyInstance method?.invoke(target, * args)
            }
        }

    }

    //  val teacher = MProxyPattern02.TeacherDao()
    //
    //    val temp = MProxyPattern02.ProxyFactory(teacher).getProxyInstance()
    //    (temp as MProxyPattern02.ITeacherDao).teacher("WZY")

}


